package com.jastar.android.game.cannon.view;

import android.content.Context;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.jastar.android.game.cannon.engine.GameEngine;
import com.jastar.android.game.cannon.model.Cannon;

public class CannonGameView extends SurfaceView implements SurfaceHolder.Callback {
    private GameEngine gameEngine;
    private SurfaceHolder holder;

    public CannonGameView(Context context) {
        super(context);
        setFocusable(true);
        setFocusableInTouchMode(true);
        holder = getHolder();
        holder.addCallback(this);
        gameEngine = new GameEngine();
        gameEngine.setSurfaceHolder(getHolder());
        gameEngine.setCanvasSize(getWidth(), getHeight());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        super.onSizeChanged(w, h, oldW, oldH);
        gameEngine.setCanvasSize(w, h);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        gameEngine.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        gameEngine.stop();
    }

    public void pause() {
        gameEngine.pause();
    }

    public void resume() {
        gameEngine.resume();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Cannon cannon = gameEngine.getCannon();
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                cannon.setAngle(Math.max(0, cannon.getAngle() + 3));
                return true;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                cannon.setAngle(Math.min(90, cannon.getAngle() - 3));
                return true;
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_BUTTON_1:
            case KeyEvent.KEYCODE_ENTER:
                gameEngine.startCharging();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_BUTTON_1:
            case KeyEvent.KEYCODE_ENTER:
                gameEngine.fireProjectile();
                return true;
        }
        return super.onKeyUp(keyCode, event);
    }

}